<template>
  <div>
    <vxe-card title="" class="w-full" :border="false">
      <AuForm
        ref="formRef"
        :formList="formList"
        labelWidth="100px"
        @submit="onsubmit"
      />
    </vxe-card>

    <vxe-card
      title=""
      class="w-full mt-[16px] h-[36vh]"
      :border="false"
      :padding="false"
    >
      <h3 class="m-[20px] mb-0 flex items-center justify-between">
        <div class="flex items-center">
          <span class="text-[--autata-font-color]"
            >{{ t("tea_infuser.dashboard.tea_powder.powder_output") }}({{
              matUnit
            }})</span
          >
        </div>
        <el-link
          type="primary"
          :underline="false"
          @click="exportExcelGroup('mat')"
        >
          {{ t("tea_infuser.dashboard.tea_powder.export") }}
        </el-link>
      </h3>
      <div
        ref="matLineChartRef"
        v-loading="matChartLoading"
        style="width: 99%; height: calc(36vh - 56px)"
      />
    </vxe-card>

    <vxe-card
      title=""
      class="mt-[16px] h-[48vh] w-full pb-4"
      :border="false"
      :padding="false"
    >
      <h3 class="m-[20px] mb-0 flex items-center justify-between">
        <span class="text-[--autata-font-color]">{{
          t(MATERIAL_TABLE_TITLE)
        }}</span>
        <el-link
          type="primary"
          :underline="false"
          @click="exportExcelGroup('mat')"
        >
          {{ t("tea_infuser.dashboard.tea_powder.export") }}
        </el-link>
      </h3>
      <div class="h-[calc(100%_-_45px)]">
        <AuTable v-if="active === 4" ref="tableMatRef" v-bind="gridOptionMat" />
      </div>
    </vxe-card>
  </div>
</template>

<script setup lang="ts">
import { AuForm } from "@/components/AuForm";
import { computed, onMounted, reactive, ref } from "vue";
import dayjs from "dayjs";
import { storeGroupSelect } from "@/utils/formSelect";
import { deviceGetList } from "@/api/teaInfuser/device";
import { getStoreList } from "@/api/teaInfuser/store";
import { getMaterialList } from "@/api/cabinet/material";
import {
  PROD_TABLE_TITLE,
  gridOptionBase,
  MATERIAL_TABLE_TITLE,
  MATERIAL_TOP_5,
  PROD_TOP_5,
  TREND_TITLE_B,
  TREND_TITLE_G
} from "@/views/teaInfuser/dashboard/analysis/constant";
import { useDark, useECharts } from "@pureadmin/utils";
import { cloneDeep } from "lodash-unified";
import {
  getFormulaCharts,
  getFormulaTopCharts,
  getMaterialCharts,
  getMaterialTopCharts
} from "@/api/cabinet/analysis";
import { MeasuringUnit, MeasuringWeight } from "@/utils/tool";
import {
  COLOR_LIST,
  DEVICE_TYPE_ENUM,
  LINE_COLOR,
  TEXT_COLOR,
  THEME_COLOR
} from "@/utils/constants";
import { AuTable } from "@/components/AuTable";
import { PropDefines } from "@/components/AuTable/type";
import exportExcel from "@/utils/exportExcel";
import { useI18n } from "vue-i18n";
import { pickerOptions } from "@/views/teaInfuser/dashboard/analysis/components/tools";

const { t } = useI18n();
const emit = defineEmits(["confirm"]);
const props = defineProps<{
  active: number;
}>();
const { isDark } = useDark();
const theme = computed(() => (isDark.value ? "dark" : "light"));

const formRef = ref();
const formList = ref([
  {
    type: "el-date-picker",
    key: "scsj",
    inType: "datetimerange",
    label: "tea_infuser.dashboard.tea_powder.production_time",
    span: 12,
    rangeSeparator: "至",
    startPlaceholder: "tea_infuser.dashboard.tea_powder.start_time",
    endPlaceholder: "tea_infuser.dashboard.tea_powder.end_time",
    valueFormat: "YYYY-MM-DD HH:mm:ss",
    ...pickerOptions(formRef),
    defaultValue: [
      dayjs().subtract(10, "day").format("YYYY-MM-DD HH:mm:ss"),
      dayjs().format("YYYY-MM-DD HH:mm:ss")
    ]
  },
  () => storeGroupSelect("group_idlist", {}, true),
  {
    type: "select",
    key: "store_id",
    label: "tea_infuser.dashboard.tea_powder.store_name",
    placeholder: "tea_infuser.dashboard.tea_powder.store_name_placeholder",
    valueKey: "id",
    labelKey: "name",
    filterable: true,
    options: []
  },
  {
    type: "select",
    key: "device_id",
    label: "tea_infuser.dashboard.tea_powder.device_code",
    placeholder: "tea_infuser.dashboard.tea_powder.device_code_placeholder",
    valueKey: "device_id",
    labelKey: "device_id",
    filterable: true,
    options: [],
    popperClass: "device-popper"
  },
  {
    type: "select",
    key: "material_id",
    label: "tea_infuser.dashboard.tea_powder.material_name",
    placeholder: "tea_infuser.dashboard.tea_powder.material_name_placeholder",
    valueKey: "material_id",
    labelKey: "name",
    filterable: true,
    options: [],
    popperClass: "device-popper"
  }
]);

const tabActive = ref("1");
const matUnit = ref("g");
const matChartLoading = ref(false);
const matLineChartRef = ref();
const { setOptions: setMatLineOptions } = useECharts(matLineChartRef, {
  theme
});

const matTopBarLoading = ref(false);
const matTopBarChartRef = ref();
const { setOptions: setMatBarOptions } = useECharts(matTopBarChartRef, {
  theme
});
const matPieChartRef = ref();
const { setOptions: setMatPieOptions } = useECharts(matPieChartRef, {
  theme
});

const gridOptionMat = reactive<PropDefines>({
  ...cloneDeep(gridOptionBase),
  columns: [
    {
      field: "index",
      title: "tea_infuser.dashboard.tea_powder.serial_number",
      width: 90
    },
    {
      field: "material_name",
      title: "tea_infuser.dashboard.tea_powder.tea_powder_name",
      width: 360
    },
    { field: "count", title: "tea_infuser.dashboard.tea_powder.count" },
    { field: "num", title: "tea_infuser.dashboard.tea_powder.total_powder" }
  ]
});

const prodChartLoading = ref(false);
const tabProdActive = ref("1");
const prodLineChartRef = ref();
const { setOptions: setProdLineOptions } = useECharts(prodLineChartRef, {
  theme
});

const prodTopBarLoading = ref(false);
const prodTopBarChartRef = ref();
const { setOptions: setProdBarOptions } = useECharts(prodTopBarChartRef, {
  theme
});
const prodPieChartRef = ref();
const { setOptions: setProdPieOptions } = useECharts(prodPieChartRef, {
  theme
});

const gridOptionProd = reactive<PropDefines>({
  ...cloneDeep(gridOptionBase),
  columns: [
    {
      field: "time",
      title: "tea_infuser.dashboard.tea_powder.production_date",
      width: 170,
      align: "center"
    },
    {
      field: "store_num",
      title: "tea_infuser.dashboard.tea_powder.store",
      minWidth: 150,
      align: "center"
    },
    {
      field: "normal_num",
      title: "tea_infuser.dashboard.tea_powder.normal_amount",
      minWidth: 150,
      align: "center"
    },
    {
      field: "unusual_num",
      title: "tea_infuser.dashboard.tea_powder.abnormal_amount",
      minWidth: 150,
      align: "center"
    },
    {
      field: "cancle_num",
      title: "tea_infuser.dashboard.tea_powder.cancel_amount",
      minWidth: 150,
      align: "center"
    }
  ]
});

const exportExcelGroup = (type: string) => {
  if (type === "mat") {
    exportExcel(
      gridOptionMat.columns,
      gridOptionMat.dataSource,
      tabActive.value === "1"
        ? t("tea_infuser.dashboard.tea_powder.summary_data")
        : MATERIAL_TABLE_TITLE
    );
  }
};

const getSearchData = () => {
  const param = cloneDeep(formRef.value.getFormData());

  const groupObjArr = [];
  if (param.group_idlist != undefined && param.group_idlist.length > 0) {
    for (const item of param.group_idlist) {
      groupObjArr.push({ group_id: item });
    }
    param["group_idlist"] = JSON.stringify(groupObjArr);
  }

  param["create_start_time"] = param.scsj[0];
  param["create_end_time"] = param.scsj[1];
  param.size = 0;
  param.start_page = 0;
  param.device_type = DEVICE_TYPE_ENUM.TEA_POWDER;
  param.hiddenDeviceType = true;

  delete param["scsj"];
  return param;
};

// region  物料数据趋势图

/**
 * 获取状态
 */
const getStatus = () => {
  let param;
  if (tabActive.value === "1") {
    // 汇总
    param = {
      groupname: "status"
    };
  } else if (tabActive.value === "2") {
    // 用料
    const statusArray = [
      { status: 1 }
      // { status: 2 },
      // { status: 4 },
      // { status: 5 },
      // { status: 6 }
    ];
    param = {
      groupname: "material_id",
      status: JSON.stringify(statusArray)
    };
  } else if (tabActive.value === "3") {
    // 补料
    const statusArray = [{ status: 3 }];
    param = {
      groupname: "material_id",
      status: JSON.stringify(statusArray)
    };
  } else if (tabActive.value === "4") {
    // 报废
    const statusArray = [{ status: 2 }, { status: 5 }, { status: 6 }];
    param = {
      groupname: "material_id",
      status: JSON.stringify(statusArray)
    };
  } else if (tabActive.value === "5") {
    // 校准
    const statusArray = [{ status: 4 }];
    param = {
      groupname: "material_id",
      status: JSON.stringify(statusArray)
    };
  }

  return param;
};

/**
 * 获取最大值和单位
 * @param list
 */
const getMaxAndUnit = (
  list: any[]
): {
  maxNum: number;
  weightUnit: "g" | "kg" | "ton";
  weightText: string;
} => {
  //得出最大值
  const liveDataNum = [];
  list.forEach((item, i) => {
    if (!isNaN(item.normal_num)) {
      liveDataNum.push(item.normal_num);
    }
    if (!isNaN(item.waste_num)) {
      liveDataNum.push(item.waste_num);
    }
    if (!isNaN(item.calibration_num)) {
      liveDataNum.push(item.calibration_num);
    }
    if (!isNaN(item.cancle_num)) {
      liveDataNum.push(item.cancle_num);
    }
    if (!isNaN(item.unusual_num)) {
      liveDataNum.push(item.unusual_num);
    }
    if (!isNaN(item.repair_num)) {
      liveDataNum.push(item.repair_num);
    }
    if (!isNaN(item.num)) {
      liveDataNum.push(item.num);
    }
  });
  let maxNum = 0;
  if (liveDataNum.length > 0) {
    maxNum = liveDataNum.reduce((max, current) => {
      return Math.max(max, current);
    });
  }
  let weightUnit: "g" | "kg" | "ton" = "ton";
  let weightText = "";
  //根据最大值得出换算的单位
  if (maxNum >= 1000000) {
    weightUnit = "ton";
    weightText = "吨";
  } else if (maxNum >= 1000) {
    weightUnit = "kg";
    weightText = "kg";
  } else {
    weightUnit = "g";
    weightText = "g";
  }

  return {
    maxNum,
    weightUnit,
    weightText
  };
};

/**
 * 设置折线图数据
 * @param xArr
 * @param allArr
 */
const setLineOptionData = (
  xArr: string[],
  allArr: { [key: string]: any[] }
) => {
  const series = [];
  let index = 0;
  for (const allArrKey in allArr) {
    series.push({
      data: allArr[allArrKey],
      type: "line",
      name: allArrKey,
      showSymbol: false,
      lineStyle: {
        color: COLOR_LIST[index]
      }
    });
    index++;
  }

  setMatLineOptions({
    title: {
      show: false
    },
    grid: {
      left: "2%",
      right: "2%",
      bottom: "6%",
      top: "6%",
      containLabel: true
    },
    color: COLOR_LIST,
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross"
      }
    },
    xAxis: {
      type: "category",
      axisTick: {
        show: false // 通过设置 show 为 false 来隐藏刻度线
      },
      axisLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      },
      axisLabel: {
        color: TEXT_COLOR
      },
      data: xArr
    },
    yAxis: {
      type: "value",
      splitLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      }
    },
    series
  });
};

const setAllData = (
  list: any[],
  xArr: string[],
  weightUnit: "g" | "kg" | "ton"
) => {
  // 用料
  const useArr = list.map(item => {
    const num =
      item.normal_num +
      item.waste_num +
      item.calibration_num +
      item.cancle_num +
      item.unusual_num;

    // return Number(MeasuringWeight(weightUnit, num));
    return Number(num);
  });
  // 补料
  const repairArr = list.map(item =>
    Number(MeasuringWeight(weightUnit, item.repair_num))
  );
  // // 报废
  // const scrapArr = list.map(item =>
  //   Number(MeasuringWeight(weightUnit, item.cancle_num + item.unusual_num))
  // );
  // // 校准
  // const calibrationArr = list.map(item =>
  //   Number(MeasuringWeight(weightUnit, item.calibration_num))
  // );

  // setLineOptionData(xArr, { 用料: useArr, 补料: repairArr });
  setLineOptionData(xArr, { 出粉量: useArr });
};

const mergeData = (data: any[]) => {
  const mergedData = [];

  // 使用一个对象来跟踪已合并的材料
  const materialMap = {};

  data.forEach(item => {
    const { material_name, num } = item;

    // 如果该材料已经存在于 materialMap 中，则累加 num 和次数
    if (materialMap[material_name]) {
      materialMap[material_name].num += num;
      materialMap[material_name].count += 1;
    } else {
      // 如果材料不存在，初始化一个新条目
      materialMap[material_name] = {
        num: num,
        count: 1,
        material_name: material_name
      };
    }
  });

  // 将合并后的对象转换为数组
  for (const key in materialMap) {
    mergedData.push(materialMap[key]);
  }

  return mergedData.map((v, i) => {
    return {
      ...v,
      index: i + 1
    };
  });
};

const setMaterialData = (list: any[], xArr: string[], weightUnit: string) => {
  gridOptionMat.columns = [
    {
      field: "index",
      title: "tea_infuser.dashboard.tea_powder.serial_number",
      width: 90
    },
    {
      field: "material_name",
      title: "tea_infuser.dashboard.tea_powder.tea_powder_name",
      width: 360
    },
    { field: "count", title: "tea_infuser.dashboard.tea_powder.count" },
    { field: "num", title: "tea_infuser.dashboard.tea_powder.total_powder" }
  ];

  gridOptionMat.dataSource = mergeData(list);
};

const getMatLineChart = async () => {
  const param = getSearchData();
  param["grouptime"] = "day";
  const statusParam = getStatus();
  try {
    const res = await getMaterialCharts({ ...param, ...statusParam });
    console.log(res);
    const list = res.data.reverse();
    const xArr = list.map(item => item.time);
    const { weightUnit } = getMaxAndUnit(list);

    setAllData(list, xArr, weightUnit);

    const statusParam1 = {
      groupname: "material_id",
      status: JSON.stringify([{ status: 1 }])
    };
    const resTable = await getMaterialCharts({ ...param, ...statusParam1 });
    setMaterialData(resTable.data, xArr, weightUnit);
  } catch (e) {}
};

const changeRadio = () => {
  getMatLineChart();
};

// endregion

// region 物料top5分布
const setTopOptionData = (xArr: string[], yArr: string[]) => {
  setMatBarOptions({
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "value",
      boundaryGap: [0, 0.01],
      splitLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      }
    },
    yAxis: {
      type: "category",
      axisTick: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      },
      axisLabel: {
        color: TEXT_COLOR
      },
      data: xArr
    },
    series: [
      {
        name: t("tea_infuser.dashboard.tea_powder.total"),
        type: "bar",
        data: yArr,
        itemStyle: {
          color: COLOR_LIST[0]
        }
      }
    ]
  });
};

const setTopPieOptionData = (data: any[]) => {
  setMatPieOptions({
    tooltip: {
      trigger: "item"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    series: [
      {
        name: t("tea_infuser.dashboard.tea_powder.ranking_ratio"),
        type: "pie",
        radius: "70%",
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        }
      }
    ]
  });
};

const getMatTopCharts = async () => {
  const param = getSearchData();
  param["grouptime"] = "day";
  const statusParam = getStatus();
  try {
    const res = await getMaterialTopCharts({ ...param, ...statusParam });
    console.log(res);
    const list = res.data;
    const xArr = list.map(item => item.material_name);
    const yArr = list.map(item => item.num).sort((a, b) => b - a);
    setTopOptionData(xArr, yArr);

    const pieData = list.map((v, i) => {
      return {
        value: v.num,
        name: v.material_name,
        itemStyle: {
          color: COLOR_LIST[i]
        }
      };
    });
    setTopPieOptionData(pieData);
  } catch (e) {}
};
// endregion

// region 生产数据趋势图
const changeProdRadio = () => {
  getProdFormulaCharts();
};

const setProdLineOptionData = (series: any[], xArr: any[]) => {
  setProdLineOptions({
    title: {
      show: false
    },
    grid: {
      left: "2%",
      right: "2%",
      bottom: "6%",
      top: "6%",
      containLabel: true
    },
    color: COLOR_LIST,
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross"
      }
    },
    xAxis: {
      type: "category",
      axisTick: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      },
      axisLabel: {
        color: TEXT_COLOR
      },
      data: xArr
    },
    yAxis: {
      type: "value",
      splitLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      }
    },
    series
  });
};

const getProdFormulaCharts = async () => {
  const param = getSearchData();
  param["grouptime"] = "day";
  if (tabProdActive.value == "1") {
    param["groupname"] = "status";
  } else if (tabProdActive.value == "2") {
    param["status"] = "1";
    param["groupname"] += "formula_subid";
  } else if (tabProdActive.value == "3") {
    param["status"] += "2";
    param["groupname"] += "formula_subid";
  }
  param["device_type"] = "";

  const res = await getFormulaCharts(param);

  const list = res.data.reverse();
  const xArr = list.map(item => item.time);
  gridOptionProd.dataSource = list;
  if (tabProdActive.value === "1") {
    const series = [
      {
        name: t("tea_infuser.dashboard.tea_powder.normal_amount"),
        type: "line",
        data: list.map(item => item.normal_num),
        showSymbol: false,
        lineStyle: {
          color: COLOR_LIST[0]
        }
      },
      {
        name: t("tea_infuser.dashboard.tea_powder.cancel_amount"),
        type: "line",
        data: list.map(item => item.cancle_num),
        showSymbol: false,
        lineStyle: {
          color: COLOR_LIST[1]
        }
      }
    ];

    gridOptionProd.columns = [
      {
        field: "time",
        title: "tea_infuser.dashboard.tea_powder.production_date",
        width: 170,
        align: "center"
      },
      {
        field: "normal_num",
        title: "tea_infuser.dashboard.tea_powder.normal_amount",
        minWidth: 150,
        align: "center"
      },
      {
        field: "unusual_num",
        title: "tea_infuser.dashboard.tea_powder.abnormal_amount",
        minWidth: 150,
        align: "center"
      },
      {
        field: "cancle_num",
        title: "tea_infuser.dashboard.tea_powder.cancel_amount",
        minWidth: 150,
        align: "center"
      }
    ];

    setProdLineOptionData(series, xArr);
  } else {
    gridOptionProd.columns = [
      {
        field: "time",
        title: "tea_infuser.dashboard.tea_powder.production_date",
        width: 170,
        align: "center"
      },
      {
        field: "formula_name",
        title: "tea_infuser.dashboard.tea_powder.product",
        minWidth: 150,
        align: "center"
      },
      {
        field: "num",
        title: "tea_infuser.dashboard.tea_powder.output",
        minWidth: 150,
        align: "center"
      }
    ];
    const series = [
      {
        name:
          tabProdActive.value === "2"
            ? t("tea_infuser.dashboard.tea_powder.normal_amount")
            : t("tea_infuser.dashboard.tea_powder.cancel_amount"),
        type: "line",
        data: list.map(item => item.num),
        showSymbol: false,
        lineStyle: {
          color: COLOR_LIST[0]
        }
      }
    ];
    setProdLineOptionData(series, xArr);
  }
};
// endregion

// region 物料top5分布
const setProdTopOptionData = (xArr: string[], yArr: string[]) => {
  setProdBarOptions({
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "value",
      boundaryGap: [0, 0.01],
      splitLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      }
    },
    yAxis: {
      type: "category",
      axisTick: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      },
      axisLabel: {
        color: TEXT_COLOR
      },
      data: xArr
    },
    series: [
      {
        name: t("tea_infuser.dashboard.tea_powder.total"),
        type: "bar",
        data: yArr,
        itemStyle: {
          color: COLOR_LIST[0]
        }
      }
    ]
  });
};

const setProdTopPieOptionData = (data: any[]) => {
  setProdPieOptions({
    tooltip: {
      trigger: "item"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    series: [
      {
        name: t("tea_infuser.dashboard.tea_powder.ranking_ratio"),
        type: "pie",
        radius: "70%",
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        }
      }
    ]
  });
};

const getProdTopCharts = async () => {
  const param = getSearchData();
  param["grouptime"] = "day";
  param["device_type"] = "";
  try {
    const res = await getFormulaTopCharts({ ...param });
    console.log(res);
    const list = res.data;
    const xArr = list.map(item => item.formula_name);
    const yArr = list.map(item => item.num).sort((a, b) => b - a);
    setProdTopOptionData(xArr, yArr);

    const pieData = list.map((v, i) => {
      return {
        value: v.num,
        name: v.formula_name,
        itemStyle: {
          color: COLOR_LIST[i]
        }
      };
    });
    setProdTopPieOptionData(pieData);
  } catch (e) {}
};
// endregion

const init = () => {
  deviceGetList({
    size: 0
  }).then(res => {
    formRef.value.setFormProps("device_id", {
      options: res.data.filter(item => item.device_model.includes("ATT-tp"))
    });
  });

  getStoreList({
    size: 0
  }).then(res => {
    formRef.value.setFormProps("store_id", {
      options: res.data
    });
  });

  getMaterialList({
    size: 0
  }).then(res => {
    formRef.value.setFormProps("material_id", {
      options: res.data
    });
  });

  onsubmit();
};

const onsubmit = () => {
  getMatLineChart();
  getMatTopCharts();
  // getProdFormulaCharts();
  // getProdTopCharts();
};

onMounted(() => {
  init();
});
</script>
